package com.boge.utils.myutils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;

/**
 * 解压 先解压tar.gz成tar 再对tar进行解压，并删除tar文件。
 * 
 * @author Administrator
 *
 */
public class Unzip {

	public static void main(String[] args) {
//		String entry = "C:/Users/Administrator/Documents/pmfile/sEthPMHistory15minTable.mib";// 需要压缩的文件夹
//		try {
//			String archive = archive(entry);// 生成tar包
//			String path = compressArchive(archive);// 生成gz包
//		} catch (Exception e) {
//			// TODO: handle exception
//		}

		// 解压
		try {
			unCompressArchiveGz("D:/NMS2/TFTP/PM/192.168.21.53_15min.tar.gz");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 先把需要压缩的文件，打包成.tar文件。 
	 * @param entry
	 * @return
	 * @throws IOException
	 */
	private static String archive(String entry) throws IOException {
        File file = new File(entry);

        TarArchiveOutputStream tos = new TarArchiveOutputStream(new FileOutputStream(file.getAbsolutePath() + ".tar"));
        String base = file.getName();
        if(file.isDirectory()){
            archiveDir(file, tos, base);
        }else{
            archiveHandle(tos, file, base);
        }

        tos.close();
        return file.getAbsolutePath() + ".tar";
    }
	
	/**
	 * 使用gzip把刚刚打包的.tar文件进行压缩（tar.gz）
	 * @param path
	 * @return
	 * @throws IOException
	 */
	public static String compressArchive(String path) throws IOException{
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path));

        GzipCompressorOutputStream gcos = new GzipCompressorOutputStream(new BufferedOutputStream(new FileOutputStream(path + ".gz")));

        byte[] buffer = new byte[1024];
        int read = -1;
        while((read = bis.read(buffer)) != -1){
            gcos.write(buffer, 0, read);
        }
        gcos.close();
        bis.close();
        return path + ".gz";
    }

/**
     * 递归处理，准备好路径
     * @param file
     * @param tos
     * @param base 
     * @throws IOException
     * @author yutao
     * @date 2017年5月27日下午1:48:40
     */
    private static void archiveDir(File file, TarArchiveOutputStream tos, String basePath) throws IOException {
        File[] listFiles = file.listFiles();
        for(File fi : listFiles){
            if(fi.isDirectory()){
                archiveDir(fi, tos, basePath + File.separator + fi.getName());
            }else{
                archiveHandle(tos, fi, basePath);
            }
        }
    }

/**
     * 具体归档处理（文件）
     * @param tos
     * @param fi
     * @param base
     * @throws IOException
     * @author yutao
     * @date 2017年5月27日下午1:48:56
     */
    private static void archiveHandle(TarArchiveOutputStream tos, File fi, String basePath) throws IOException {
        TarArchiveEntry tEntry = new TarArchiveEntry(basePath + File.separator + fi.getName());
        tEntry.setSize(fi.length());

        tos.putArchiveEntry(tEntry);

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fi));

        byte[] buffer = new byte[1024];
        int read = -1;
        while((read = bis.read(buffer)) != -1){
            tos.write(buffer, 0 , read);
        }
        bis.close();
        tos.closeArchiveEntry();//这里必须写，否则会失败
    }

	/**
	 * 解压tar.gz成tar
	 * 
	 * @param archive
	 * @throws IOException
	 */
	private static void unCompressArchiveGz(String archive) throws IOException {

		File file = new File(archive);

		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
				file));

		String fileName = file.getName().substring(0,
				file.getName().lastIndexOf("."));

		String finalName = file.getParent() + File.separator + fileName;

		BufferedOutputStream bos = new BufferedOutputStream(
				new FileOutputStream(finalName));

		GzipCompressorInputStream gcis = new GzipCompressorInputStream(bis);

		byte[] buffer = new byte[1024];
		int read = -1;
		while ((read = gcis.read(buffer)) != -1) {
			bos.write(buffer, 0, read);
		}
		gcis.close();
		bos.close();

		unCompressTar(finalName);
	}

	/**
	 * 对tar进行解压，并删除tar文件
	 * 
	 * @param finalName
	 * @throws IOException
	 */
	private static void unCompressTar(String finalName) throws IOException {

		File file = new File(finalName);
		//解压到当前文件夹
		String parentPath = finalName.substring(0, finalName.indexOf(".tar"));
		TarArchiveInputStream tais = new TarArchiveInputStream(
				new FileInputStream(file));

		TarArchiveEntry tarArchiveEntry = null;

		while ((tarArchiveEntry = tais.getNextTarEntry()) != null) {
			String name = tarArchiveEntry.getName();
			File tarFile = new File(parentPath, name);
			if (!tarFile.getParentFile().exists()) {
				tarFile.getParentFile().mkdirs();
			}

			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(tarFile));

			int read = -1;
			byte[] buffer = new byte[1024];
			while ((read = tais.read(buffer)) != -1) {
				bos.write(buffer, 0, read);
			}
			bos.close();
		}
		tais.close();
		file.delete();// 删除tar文件
	}

}
